package com.schoolhelper.login.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.schoolhelper.login.domain.User;
import com.schoolhelper.login.service.impl.AuthServiceImpl;
import com.schoolhelper.utils.JwtUtils;  // 添加JWT工具类导入
import com.schoolhelper.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

// 1. 将@Controller改为@RestController（返回JSON数据）
@RestController
@RequestMapping("/api/auth")
// 2. 添加跨域支持
@CrossOrigin(origins = "http://localhost:8080")  // 允许前端地址访问
public class LoginController {
    @Autowired
    private AuthServiceImpl userLoginServicesImpl;
    @Autowired
    private JwtUtils jwtUtils;  // 注入JWT工具类
    @Autowired
    private FileUploadConfig fileUploadConfig;

    // 3. 使用@RequestBody接收JSON参数
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginData) {
        Map<String, Object> response = new HashMap<>();
        String account = loginData.get("account");
        String password = loginData.get("password");

        User user = userLoginServicesImpl.authenticate(account, password);
        if (user != null) {
            // 处理头像URL
            if (user.getAvatar() != null && !user.getAvatar().isEmpty() && !user.getAvatar().startsWith("http")) {
                user.setAvatar(fileUploadConfig.getFileUrl(user.getAvatar()));
            }
            
            response.put("success", true);
            // 替换原有token生成逻辑为JWT
            String token = jwtUtils.generateToken(String.valueOf(user.getId()));  // 使用用户ID生成JWT
            response.put("token", token);
            response.put("user", user);
            // 判断用户信息是否完整
            boolean infoComplete = true;
            if (user.getSchoolNum() == null || user.getSchoolNum().trim().isEmpty()
                || user.getSchoolName() == null || user.getSchoolName().trim().isEmpty()
                || user.getMajor() == null || user.getMajor().trim().isEmpty()
                || user.getGrade() == null || user.getGrade().trim().isEmpty()
                || user.getClassNum() == null || user.getClassNum().trim().isEmpty()
                || user.getEmail() == null || user.getEmail().trim().isEmpty()
                || user.getAddress() == null || user.getAddress().trim().isEmpty()) {
                infoComplete = false;
            }
            System.out.println("用户信息完整性检查 - 用户ID: " + user.getId() + ", infoComplete: " + infoComplete);
            System.out.println("学号: '" + user.getSchoolNum() + "', 学校: '" + user.getSchoolName() + "', 专业: '" + user.getMajor() + "'");
            System.out.println("年级: '" + user.getGrade() + "', 班级: '" + user.getClassNum() + "', 邮箱: '" + user.getEmail() + "', 地址: '" + user.getAddress() + "'");
            response.put("infoComplete", infoComplete);
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误");
        }
        return response;  // 返回JSON数据
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody String userJson) {
        Map<String, Object> response = new HashMap<>();
        
        if (userJson == null) {
            response.put("success", false);
            response.put("message", "请将注册信息填写完整");
            return response;
        }
        
        JSONObject userJsonObject = JSON.parseObject(userJson);
        String account = userJsonObject.getString("account");
        String password = userJsonObject.getString("password");
        String phone = userJsonObject.getString("phone");
        String userName = userJsonObject.getString("username");
        
        // 参数完整性校验
        if (account.isEmpty() || password.isEmpty() || phone.isEmpty() || userName.isEmpty()) {
            response.put("success", false);
            response.put("message", "请将注册信息填写完整");
            return response;
        }
        
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        user.setPhone(phone);
        user.setUsername(userName);
        
        String registerStatus = userLoginServicesImpl.userRegiste(user, account);
        switch (registerStatus) {
            case "success":
                response.put("success", true);
                response.put("message", "注册成功");
                break;
            case "account_exists":
                response.put("success", false);
                response.put("message", "账号已存在");
                break;
            case "db_error":
                response.put("success", false);
                response.put("message", "注册失败，请稍后重试");
                break;
            default:
                response.put("success", false);
                response.put("message", "注册失败，请检查输入信息");
        }
        
        return response;
    }

    // 根据用户ID获取用户信息
    @GetMapping("/user/{userId}")
    public Map<String, Object> getUserById(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            User user = userLoginServicesImpl.getUserById(userId);
            if (user != null) {
                // 处理头像URL
                if (user.getAvatar() != null && !user.getAvatar().isEmpty() && !user.getAvatar().startsWith("http")) {
                    user.setAvatar(fileUploadConfig.getFileUrl(user.getAvatar()));
                }
                
                response.put("success", true);
                response.put("user", user);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取用户信息失败");
        }
        return response;
    }
}